<template>
  <div class="mcp-tools">
    <h2>MCP 工具列表</h2>
    
    <!-- 工具列表 -->
    <el-collapse v-model="activeTools">
      <el-collapse-item
        v-for="tool in tools"
        :key="tool.name"
        :title="tool.name"
        :name="tool.name"
      >
        <template #title>
          <span class="tool-title">{{ tool.name }}</span>
          <el-tag size="small" type="info" class="tool-description">
            {{ tool.description }}
          </el-tag>
        </template>

        <!-- 工具参数表单 -->
        <el-form
          :model="toolParams[tool.name]"
          :rules="toolRules[tool.name]"
          ref="toolFormRefs"
          label-width="120px"
          class="tool-form"
        >
          <template v-if="tool.parameters && tool.parameters.properties">
            <el-form-item
              v-for="(prop, key) in tool.parameters.properties"
              :key="key"
              :label="prop.description || key"
              :prop="key"
            >
              <!-- 根据参数类型渲染不同的输入控件 -->
              <el-input
                v-if="prop.type === 'string'"
                v-model="toolParams[tool.name][key]"
                :placeholder="prop.description"
              />
              <el-input-number
                v-else-if="prop.type === 'number'"
                v-model="toolParams[tool.name][key]"
                :min="prop.minimum"
                :max="prop.maximum"
              />
              <el-switch
                v-else-if="prop.type === 'boolean'"
                v-model="toolParams[tool.name][key]"
              />
              <el-select
                v-else-if="prop.enum"
                v-model="toolParams[tool.name][key]"
                :placeholder="prop.description"
              >
                <el-option
                  v-for="option in prop.enum"
                  :key="option"
                  :label="option"
                  :value="option"
                />
              </el-select>
            </el-form-item>
          </template>

          <!-- 执行按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              @click="executeTool(tool)"
              :loading="executing[tool.name]"
            >
              执行
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 执行结果 -->
        <div v-if="executionResults[tool.name]" class="execution-result">
          <h4>执行结果：</h4>
          <pre>{{ executionResults[tool.name] }}</pre>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'McpTools',
  setup() {
    const tools = ref([])
    const activeTools = ref([])
    const toolParams = reactive({})
    const toolRules = reactive({})
    const executing = reactive({})
    const executionResults = reactive({})
    const toolFormRefs = ref({})

    // 获取工具列表
    const fetchTools = async () => {
      try {
        const response = await axios.get('/api/v1/tools')
        if (response.data.tools) {
          tools.value = response.data.tools
          // 初始化每个工具的参数和规则
          tools.value.forEach(tool => {
            toolParams[tool.name] = {}
            toolRules[tool.name] = {}
            
            if (tool.parameters && tool.parameters.properties) {
              Object.entries(tool.parameters.properties).forEach(([key, prop]) => {
                // 设置默认值
                toolParams[tool.name][key] = prop.default || ''
                
                // 设置验证规则
                toolRules[tool.name][key] = [{
                  required: tool.parameters.required?.includes(key),
                  message: `${prop.description || key} 是必填项`,
                  trigger: 'blur'
                }]
              })
            }
          })
        }
      } catch (error) {
        ElMessage.error('获取工具列表失败：' + error.message)
      }
    }

    // 执行工具
    const executeTool = async (tool) => {
      if (executing[tool.name]) return
      
      try {
        executing[tool.name] = true
        executionResults[tool.name] = '正在执行...'

        // 创建 EventSource 连接
        const eventSource = new EventSource(`/api/v1/tools/${tool.name}/execute?${new URLSearchParams(toolParams[tool.name])}`)
        
        // 处理 SSE 消息
        eventSource.onmessage = (event) => {
          try {
            const data = JSON.parse(event.data)
            if (data.error) {
              executionResults[tool.name] = `错误：${data.error}`
            } else {
              executionResults[tool.name] = JSON.stringify(data.result, null, 2)
            }
          } catch (e) {
            executionResults[tool.name] = event.data
          }
        }

        // 处理错误
        eventSource.onerror = (error) => {
          executionResults[tool.name] = `执行出错：${error.message}`
          eventSource.close()
          executing[tool.name] = false
        }

        // 处理完成
        eventSource.addEventListener('complete', () => {
          eventSource.close()
          executing[tool.name] = false
        })

      } catch (error) {
        executionResults[tool.name] = `执行失败：${error.message}`
        executing[tool.name] = false
      }
    }

    onMounted(() => {
      fetchTools()
    })

    return {
      tools,
      activeTools,
      toolParams,
      toolRules,
      executing,
      executionResults,
      toolFormRefs,
      executeTool
    }
  }
}
</script>

<style scoped>
.mcp-tools {
  padding: 20px;
}

.tool-title {
  font-weight: bold;
  margin-right: 10px;
}

.tool-description {
  font-size: 12px;
}

.tool-form {
  margin-top: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.execution-result {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.execution-result pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style> 